package com.school.gmz.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.gmz.common.Result;
import com.school.gmz.entity.Message;
import com.school.gmz.mapper.MessageMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/message")
@Api(tags = "留言管理") // 定义API的分类
public class MessageController {
    @Resource
    MessageMapper messageMapper;

    // 添加留言
    @PostMapping
    @ApiOperation(value = "添加留言", notes = "创建一个新的留言记录")
    public Result<?> save(@RequestBody Message message){
        messageMapper.insert(message);
        return Result.success();
    }

    // 更新留言
    @PutMapping
    @ApiOperation(value = "更新留言", notes = "根据ID更新留言记录")
    public Result<?> update(@RequestBody Message message){
        messageMapper.updateById(message);
        return Result.success();
    }

    // 删除留言
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除留言", notes = "根据ID删除留言记录")
    public Result<?> delete(@ApiParam(value = "留言ID", required = true) @PathVariable Long id){
        messageMapper.deleteById(id);
        return Result.success();
    }

    // 查询留言
    @GetMapping
    @ApiOperation(value = "查询留言", notes = "支持名字、电话号、关键字搜索")
    public Result<?> findPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam(value = "名字", defaultValue = "") @RequestParam(defaultValue = "") String name,
            @ApiParam(value = "电话号", defaultValue = "") @RequestParam(defaultValue = "") String phone,
            @ApiParam(value = "搜索关键字", defaultValue = "") @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<Message> wrapper = Wrappers.<Message>lambdaQuery();
        if (StrUtil.isNotBlank(name)){
            wrapper.like(Message::getName, name);
        }
        if (StrUtil.isNotBlank(phone)){
            wrapper.like(Message::getPhone, phone);
        }
        if (StrUtil.isNotBlank(search)){
            wrapper.like(Message::getMessage, search);
        }
        Page<Message> messagePage = messageMapper.selectPage(new Page<>(pageNum, pageSize), wrapper); // 默认分页参数
        return Result.success(messagePage);
    }

    // 根据ID查询留言
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询留言", notes = "根据留言ID查询留言记录")
    public Result<?> findById(@ApiParam(value = "留言ID", required = true) @PathVariable Long id){
        Message message = messageMapper.selectById(id);
        if (message != null) {
            return Result.success(message);
        } else {
            return Result.failure("留言不存在");
        }
    }
}